package org.jmh.gift.rocketmq.listener;

import org.jmh.gift.contants.PayConstants;
import org.jmh.gift.service.IPayAliService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 支付宝支付成功的本地事务监听器
 */
@Component
@RocketMQTransactionListener(txProducerGroup = PayConstants.ALI_PAY_NOTIFY_TX_PRODUCER_GROUP)
public class AliPayNotifyLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayAliService payNotifyService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        byte[] payload = (byte[])msg.getPayload();
        String s = new String(payload);
        JSONObject jsonObject = JSONObject.parseObject(s);
        try {
            payNotifyService.aliPayExecute(jsonObject);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        byte[] payload = (byte[])msg.getPayload();
        String s = new String(payload);
        JSONObject jsonObject = JSONObject.parseObject(s);

        try {
            Boolean flag = payNotifyService.aliPayCheck(jsonObject);
            if(flag){
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
